/**
 * 性能监控工具 - 适老化优化版本
 * 专门针对老年人使用场景的性能监控
 */

class PerformanceMonitor {
  constructor() {
    this.metrics = {
      pageLoad: {},
      userInteraction: {},
      memoryUsage: {},
      networkRequests: {}
    }
    this.startTime = Date.now()
    this.isEnabled = true
  }

  // 开始计时
  startTiming(name, category = 'general') {
    if (!this.isEnabled) return
    
    const timingKey = `${category}_${name}`
    this.metrics[category] = this.metrics[category] || {}
    this.metrics[category][timingKey] = {
      startTime: Date.now(),
      endTime: null,
      duration: null
    }
    
    console.log(`[性能监控] 开始计时: ${timingKey}`)
  }

  // 结束计时
  endTiming(name, category = 'general') {
    if (!this.isEnabled) return
    
    const timingKey = `${category}_${name}`
    const timing = this.metrics[category]?.[timingKey]
    
    if (timing) {
      timing.endTime = Date.now()
      timing.duration = timing.endTime - timing.startTime
      
      console.log(`[性能监控] 结束计时: ${timingKey}, 耗时: ${timing.duration}ms`)
      
      // 适老化性能阈值检查
      this.checkElderlyPerformanceThresholds(timingKey, timing.duration, category)
    }
  }

  // 记录用户交互
  recordUserInteraction(action, element, responseTime) {
    if (!this.isEnabled) return
    
    const interaction = {
      action,
      element,
      responseTime,
      timestamp: Date.now(),
      userAgent: navigator.userAgent || 'unknown'
    }
    
    this.metrics.userInteraction[`${action}_${Date.now()}`] = interaction
    
    // 检查响应时间是否适合老年人
    if (responseTime > 1000) { // 超过1秒的响应时间
      console.warn(`[适老化警告] 交互响应时间过长: ${action}, ${responseTime}ms`)
      this.reportSlowInteraction(interaction)
    }
  }

  // 记录内存使用情况
  recordMemoryUsage() {
    if (!this.isEnabled) return
    
    const memory = {
      timestamp: Date.now(),
      usedJSHeapSize: performance.memory?.usedJSHeapSize || 0,
      totalJSHeapSize: performance.memory?.totalJSHeapSize || 0,
      jsHeapSizeLimit: performance.memory?.jsHeapSizeLimit || 0
    }
    
    this.metrics.memoryUsage[Date.now()] = memory
    
    // 检查内存使用是否过高
    const memoryUsagePercent = (memory.usedJSHeapSize / memory.jsHeapSizeLimit) * 100
    if (memoryUsagePercent > 80) {
      console.warn(`[适老化警告] 内存使用率过高: ${memoryUsagePercent.toFixed(2)}%`)
      this.reportHighMemoryUsage(memory)
    }
  }

  // 记录网络请求
  recordNetworkRequest(url, method, duration, success) {
    if (!this.isEnabled) return
    
    const request = {
      url,
      method,
      duration,
      success,
      timestamp: Date.now()
    }
    
    this.metrics.networkRequests[`${method}_${Date.now()}`] = request
    
    // 检查网络请求是否过慢
    if (duration > 5000) { // 超过5秒的请求
      console.warn(`[适老化警告] 网络请求过慢: ${url}, ${duration}ms`)
      this.reportSlowNetworkRequest(request)
    }
  }

  // 适老化性能阈值检查
  checkElderlyPerformanceThresholds(timingKey, duration, category) {
    const thresholds = {
      pageLoad: 3000,      // 页面加载不超过3秒
      userInteraction: 500, // 用户交互响应不超过500ms
      networkRequest: 2000, // 网络请求不超过2秒
      general: 1000        // 一般操作不超过1秒
    }
    
    const threshold = thresholds[category] || thresholds.general
    
    if (duration > threshold) {
      console.warn(`[适老化警告] ${timingKey} 耗时 ${duration}ms，超过阈值 ${threshold}ms`)
      this.reportPerformanceIssue(timingKey, duration, threshold, category)
    }
  }

  // 报告性能问题
  reportPerformanceIssue(timingKey, duration, threshold, category) {
    const issue = {
      type: 'performance',
      timingKey,
      duration,
      threshold,
      category,
      timestamp: Date.now(),
      severity: duration > threshold * 2 ? 'high' : 'medium'
    }
    
    // 在实际应用中，这里可以发送到监控服务
    console.error('[性能问题]', issue)
    
    // 可以触发用户友好的提示
    this.showPerformanceWarning(issue)
  }

  // 显示性能警告
  showPerformanceWarning(issue) {
    // 在实际应用中，这里可以显示用户友好的警告
    if (issue.severity === 'high') {
      uni.showToast({
        title: '应用运行较慢，正在优化...',
        icon: 'loading',
        duration: 2000
      })
    }
  }

  // 报告慢交互
  reportSlowInteraction(interaction) {
    console.warn('[慢交互]', interaction)
    // 可以在这里实现用户反馈收集
  }

  // 报告高内存使用
  reportHighMemoryUsage(memory) {
    console.warn('[高内存使用]', memory)
    // 可以在这里实现内存清理建议
  }

  // 报告慢网络请求
  reportSlowNetworkRequest(request) {
    console.warn('[慢网络请求]', request)
    // 可以在这里实现网络优化建议
  }

  // 获取性能报告
  getPerformanceReport() {
    const report = {
      totalRuntime: Date.now() - this.startTime,
      metrics: this.metrics,
      summary: this.generateSummary()
    }
    
    return report
  }

  // 生成性能摘要
  generateSummary() {
    const summary = {
      totalInteractions: Object.keys(this.metrics.userInteraction).length,
      averageResponseTime: this.calculateAverageResponseTime(),
      memoryPeak: this.calculateMemoryPeak(),
      slowOperations: this.findSlowOperations(),
      recommendations: this.generateRecommendations()
    }
    
    return summary
  }

  // 计算平均响应时间
  calculateAverageResponseTime() {
    const interactions = Object.values(this.metrics.userInteraction)
    if (interactions.length === 0) return 0
    
    const totalTime = interactions.reduce((sum, interaction) => sum + interaction.responseTime, 0)
    return Math.round(totalTime / interactions.length)
  }

  // 计算内存峰值
  calculateMemoryPeak() {
    const memoryUsages = Object.values(this.metrics.memoryUsage)
    if (memoryUsages.length === 0) return 0
    
    return Math.max(...memoryUsages.map(m => m.usedJSHeapSize))
  }

  // 查找慢操作
  findSlowOperations() {
    const slowOps = []
    
    Object.entries(this.metrics).forEach(([category, timings]) => {
      Object.entries(timings).forEach(([key, timing]) => {
        if (timing.duration && timing.duration > 1000) {
          slowOps.push({
            key,
            category,
            duration: timing.duration
          })
        }
      })
    })
    
    return slowOps.sort((a, b) => b.duration - a.duration)
  }

  // 生成优化建议
  generateRecommendations() {
    const recommendations = []
    const summary = this.generateSummary()
    
    if (summary.averageResponseTime > 500) {
      recommendations.push('考虑优化用户交互响应时间')
    }
    
    if (summary.memoryPeak > 50 * 1024 * 1024) { // 50MB
      recommendations.push('考虑优化内存使用，减少内存占用')
    }
    
    if (summary.slowOperations.length > 0) {
      recommendations.push('优化慢操作，提升用户体验')
    }
    
    return recommendations
  }

  // 清理旧数据
  cleanup() {
    const now = Date.now()
    const maxAge = 30 * 60 * 1000 // 30分钟
    
    Object.keys(this.metrics).forEach(category => {
      Object.keys(this.metrics[category]).forEach(key => {
        const item = this.metrics[category][key]
        if (item.timestamp && now - item.timestamp > maxAge) {
          delete this.metrics[category][key]
        }
      })
    })
  }

  // 启用/禁用监控
  setEnabled(enabled) {
    this.isEnabled = enabled
  }

  // 重置监控数据
  reset() {
    this.metrics = {
      pageLoad: {},
      userInteraction: {},
      memoryUsage: {},
      networkRequests: {}
    }
    this.startTime = Date.now()
  }
}

// 创建全局实例
const performanceMonitor = new PerformanceMonitor()

// 定期清理数据
setInterval(() => {
  performanceMonitor.cleanup()
}, 5 * 60 * 1000) // 每5分钟清理一次

export { performanceMonitor, PerformanceMonitor }
